package client.comm.baoding.ui.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import client.comm.commlib.network.data.JsonResult
import client.comm.commlib.network.data.Ret
import client.comm.commlib.out_time
import client.comm.commlib.toast.toast
import client.comm.baoding.ui.viewmodel.MiddleVm
import client.comm.baoding.api.bean.UserInfo
import client.comm.commlib.utils.StoreUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import retrofit2.Response

class FejViewModel(val app: Application) : MiddleVm(app) {
    val call = MutableLiveData<JsonResult<Ret>>()
    val isShowing = MutableLiveData<Boolean>()
    val gmMyRet = MutableLiveData<JsonResult<Ret>>()
    val callUser = MutableLiveData<JsonResult<UserInfo>>()

    val currLabel = MutableLiveData<String>("11")

    val userInfo = MutableLiveData<UserInfo>()

    fun gmClick(it: String, num: String) {
        runBlocking {
            isShowing.value = true
            flow {
                var emm: Response<JsonResult<Ret>>? = null
                out_time {
                    val ret = server.validatePayPwd(it)
                    emm = ret
                }
                emit(emm)
            }.map {
                var emm: Response<JsonResult<Ret>>? = it
                it?.body()?.let {
                    if (it.isSuccess) {
                        out_time {
                            val ret = server.transfer_wallet(num)
                            emm = ret
                        }
                    }
                }
                emm
            }.flowOn(Dispatchers.IO)
                .onCompletion {
                    isShowing.postValue(false)
                }.catch { cause ->
                    if (cause != null) {
//                        toast(cause.message)
                        toast("网络错误")
                    }
                }.collectLatest {
                    gmMyRet.value = it?.body()

                }
        }
    }
    fun userInfo() {
        hold({
            server.userinfo().apply {
                body()?.let {
                    if (it.isSuccess) {
                        StoreUtil.saveBean(getApplication(), it.data!!)
                    }
                }
            }
        }, success = {
            callUser.value = it
        })
    }
}